<?php

/*spy*/
//include('class.db.php');

//global $MYSQL_SEZIONI;

class ArchivioWriter
{

  /**
   * 
   * DEFINISCI TU FILE_ARCH
   * 
   */
   
	var $theFileName = "";
	var $theDirectory="";
	var $s_query = "";
	var $namefile = "";
	var $m_handle;
	var $dataS = "";
	var $dataE = "";
	var $sezione = "";

      // Costruttore 
	function __construct($start_data,$end_data,$sezioni,$dir){ 
	  
	  echo $start_data;
	  echo $end_data;
	  echo $sezioni;
          $this->theDirectory=$dir;
	} 

	function close()
	{
		if ($this->m_handle != FALSE)
		{
			fclose($this->m_handle) ;
		}
	}
	
	/** funzione writeFile().\n
	* Scrive il file di archivio namefilegiornosett giorno mese anno.txt che riporta i rusultati 
	* di archivio presenti nel DB 
	* @param  void
	* @return 0 
	*/
	function writeFile($s_query,$namefile,$header_str)
	{
	
          /*Create Directory
	   Note: name of directory could be changed
	  */
          $dir_archivio=$this->theDirectory.$namefile;

          if (is_dir($dir_archivio) ){
		  echo "Directory is present \n";
	  } else {
		  mkdir($dir_archivio, 0777); //directory creation 
		  echo "<br>\r Creation Directory $dir_archivio <br> ";
	  }
		
	  /*
	    QUERY to modify
	  */

          
	  $piezo_query = $s_query;
	  
          
          echo "<br> QUERY: ".$piezo_query."<br>";
          
	 	
	  //$this->theFileName = $this->theDirectory.$namefile. "_" .$datacreation. ".txt";
  	  $this->theFileName = $dir_archivio.'/'.$namefile. ".txt";
        	  		
	  if (file_exists($this->theFileName))
	  {
		  $this->m_handle = @fopen($this->theFileName, 'a') ;
	  }
	  else
	  {
		  echo "<br> Open File to write <br>".$this->theFileName;
                  $this->m_handle = @fopen($this->theFileName, 'w') ;
	  }	
	  if ($this->m_handle == FALSE)
	  {
		  trigger_error('Failed to open archivio file: ' . $this->theFileName . '\n' .
			  'Current working directory: ' . getcwd(), E_USER_WARNING) ;
	  }       
        
          $arr=$this->ExcuteQuery($piezo_query);
          $return=count($arr);
          $headerFile=str_replace(",", "\t", $header_str);
           // scrivo il file se la query eseguita mi ritorna risultato 
          if ($return>0)
          {
              $return=$dir_archivio;
              echo "<br> \r Execute Query return data following data <br>";
              
              $this->WriteHeader();
              fprintf($this->m_handle,"Data\t\tOra\t\t%s\n", $headerFile);
          
                for ($row = 0; $row < count($arr); $row++)
                {
                        for ($col=0;$col<count($arr[$row]) ; $col++)
                        {
                            if($col==0)
                            {
                                    $ora=explode (" ",$arr[$row][$col]);
                                    $separa=explode ("-",$ora[0]);
                                    $a=$separa[0];
                                    $b=$separa[1];
                                    $c=$separa[2];
                                    $data_convertita="$c/$b/$a";
                                    $oraconvertita = str_replace(":", ".", $ora[1]);
                                    fprintf($this->m_handle,"%s\t%s\t", $data_convertita,$oraconvertita);
                                    //fwrite($this->m_handle,$data_convertita. "\t". $oraconvertita);
                            }
                            else
                            {
                                if($arr[$row][$col] == 0 ||$arr[$row][$col] == 1 ||$arr[$row][$col] == 2 ||$arr[$row][$col] == 3)
                                    fprintf($this->m_handle,"%d\t\t", $arr[$row][$col]);
                                else
                                    fprintf($this->m_handle,"%e\t", $arr[$row][$col]);
//                                fwrite($this->m_handle,"\t" .$arr[$row][$col]);
                                //echo "\t". $arr[$row][$col]; //Success in Create and write with append mode
                            }
                        }
                        //echo "<br>";
                        fwrite($this->m_handle,"\r\n");
                        //echo "<br>";
                } 

	    }
	    @fclose($this->m_handle);
	    $path=$this->theDirectory;
            //echo "<br> BEFORE getDirectorySize <br>";
            //ERROR
	    //$tar=$this->getDirectorySize($path);		
            //echo "<br> AFTER getDirectorySize <br>";   
	    return $return;
	}
        
        function ExcuteQuery($piezo_query)
        {
            $msql  = new Db;
	    $msql->connect();			
	    
	    $arr=$msql->execute_select($piezo_query);
	    
	    $msql->disconnettiDB();
            
            return $arr;
            
        }
        
        function WriteHeader()
        {        
             /*			
                                Header
                */

                $data=strftime('%d-%m-%Y %H:%M:%S',time());
              fwrite($this->m_handle,"     ------------------------------------------------------------------------------------------------\r\n");
              fwrite($this->m_handle,"     |                                                                                               |\r\n");
              fwrite($this->m_handle,"     |                                                                                               |\r\n");
              fwrite($this->m_handle,"     |                                        File creato il  ". $data. "                    |\r\n"); 
              fwrite($this->m_handle,"     |                                                                                               |\r\n");
              fwrite($this->m_handle,"     |                                                                                               |\r\n");
              fwrite($this->m_handle,"     |                                                                                               |\r\n");
              fwrite($this->m_handle,"     ------------------------------------------------------------------------------------------------\r\n");
              
              //fwrite($this->m_handle,"Data\t\t  Ora\t\tP1Pz01\tP2Pz02\tP2Pz03\tP3Pz04\tP3Pz05\tP4Pz06\tP4Pz07\tP4Pz08\tP5Pz09\tP5Pz10\tP6Pz11\tP6Pz12\tP6Pz13\tP7Pz14\tP7Pz15\tP7Pz16\tP8Pz17\tP8Pz18\tP8Pz19\tP9Pz20\tP9Pz21\tP9Pz22\tP10Pz23\tP10Pz24\tP10Pz25\tP11Pz26\tP11Pz27\tP11Pz28\tP12Pz29\tP12Pz30\tP13Pz31\tP13Pz32\tP13Pz33\tP14Pz34\tP14Pz35\tP14Pz36\tP15Pz37\r\n");

              //fprintf(fwrite($this->m_handle, "%04d-%02d-%02d", $year, $month, $day);
              /*			
                              END Header
              */

              echo "<br> \r Write Header <br>";
              echo "<br>";

        }

	function Zip($zipName,$file,$web=true)
	{	
		
		$zip = new ZipArchive();
                
                $timecreation = strftime ("%d-%m-%Y-%H:%M:%S");
                //$zipName = $zipName."_".$timecreation; 
                
                echo "ZIP NAME:".$zipName;
                echo "<br>";
                echo "ZIP DIRECTORY:".$zipName;
		
		if ($zip->open("$zipName.zip", ZIPARCHIVE::CREATE)!==TRUE) {
			exit("cannot open <$filename>\n");
		}
                echo "<br> Current Zip Directory: ".$zipName;
                echo "<br>";

                $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($zipName."/"));
		// iterate over the directory
		// add each file found to the archive
		foreach ($iterator as $key=>$value)
		{
                        echo $key . ': ' . filesize($key) . ' bytes - ';
			$zip->addFile($key, basename($key)) or die ("ERROR: Could not add file: $key");
		}

		echo "<br> numfiles: " . $zip->numFiles . "<br>";
		// close and save archive
		$zip->close();
                
               
                if($web)
                {
                    header('Cache-control: private');
                    header('Content-type: application/zip');
                    header('Content-Length: '.filesize("$zipName.zip"));
                    header('Content-Disposition: filename='."$file.zip");
                    ob_clean();
                    flush();

                    # begin download
                    readfile("$zipName.zip") or die("error!");

                    $this->rrmdir($zipName);
                    unlink("$zipName.zip");
                }
	}
        
        function rrmdir($dir) {
           if (is_dir($dir)) {
             $objects = scandir($dir);
             foreach ($objects as $object) {
               if ($object != "." && $object != "..") {
                 if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
               }
             }
             reset($objects);
             rmdir($dir);
           }
         } 
         
	function FindExts($filename) 
	{
		$filename = srtlower($filename);
		$exts = split("[/\\.]",$filename);
		$n = count($exts)-1;
		$exts = $exts[$n];
		return $exts;
	}
        
	function getDirectorySize($path)
	{
	  $totalsize = 0;
	  $totalcount = 0;
	  $dircount = 0;
	  
          //echo "getDirectorySize\n"; 
          
	  if ($handle = opendir ($path))
	  {
		//echo "<br> OpenDir <br>";
		while (false !== ($file = readdir($handle)))
		{
		  //echo "<br> WHILE <br>";
		  $nextpath = $path . '/' . $file;
		  if ($file != '.' && $file != '..' && !is_link ($nextpath))
		  {
			if (is_dir ($nextpath))
			{
			  $dircount++;
			  $result = getDirectorySize($nextpath);
			  $totalsize += $result['size'];
			  $totalcount += $result['count'];
			  $dircount += $result['dircount'];
			}
			elseif (is_file ($nextpath))
			{
			  $totalsize += filesize ($nextpath);
			  $totalcount++;
			}
		  }
		}
	  }
	  closedir ($handle);
	  $total['size'] = $totalsize;
	  $total['count'] = $totalcount;
	  $total['dircount'] = $dircount;
          
          echo "<h4>Details for the path : $path</h4>";
	  echo "Total size : ".$this->sizeFormat($total['size'])."<br>";
	  echo "No. of files : ".$totalcount."<br>";
	  echo "No. of directories : ".$dircount."<br>";
          
	  return $total;
	}

	
	function sizeFormat($size)
	{
		if($size<1024)
		{
			return $size." bytes";
		}
		else if($size<(1024*1024))
		{
			$size=round($size/1024,1);
			return $size." KB";
		}
		else if($size<(1024*1024*1024))
		{
			$size=round($size/(1024*1024),1);
			return $size." MB";
		}
		else
		{
			$size=round($size/(1024*1024*1024),1);
			return $size." GB";
		}

	}  



}	

//Class Test
//$s_query ="";
//$fw = new ArchivioWriter("","","");

//Class Test con vistaDati.php
//$s_query="SELECT data,$MYSQL_SEZIONI FROM dati_impianto where data >= '$start_data' and data <= '$end_data';";

//Class Test
//$archivio_dir=$fw->writeFile($s_query,"archivio");
//$fw->Zip("archivio/archivio_15-10-2011-00:52:13","archivio_15-10-2011-00:52:13");
	    
	


?>